package service

import (
	"QHMedLink/model"
	"fmt"

	"github.com/jinzhu/gorm"
)

func CreateCustomerService(db *gorm.DB, qrCodeURL string) (*model.CustomerService, error) {
	newService := &model.CustomerService{
		QrCodeURL: qrCodeURL,
	}
	if err := db.Create(newService).Error; err != nil {
		return nil, fmt.Errorf("创建失败: %v", err)
	}
	return newService, nil
}

// 根据ID查询单个记录
func GetByID(db *gorm.DB, id int) (*model.CustomerService, error) {
	var result model.CustomerService
	if err := db.Where("service_id = ?", id).First(&result).Error; err != nil {
		return nil, fmt.Errorf("记录不存在: %v", err)
	}
	return &result, nil
}

// 查询全部记录
func GetAll(db *gorm.DB) ([]model.CustomerService, error) {
	var services []model.CustomerService
	if err := db.Find(&services).Error; err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}
	return services, nil
}

func UpdateService(db *gorm.DB, id int, newURL string) error {
	return db.Model(&model.CustomerService{}).
		Where("service_id = ?", id).
		Update("qr_code_url", newURL).Error
}

// 或使用结构体更新
func UpdateServiceStruct(db *gorm.DB, id int, updates map[string]interface{}) error {
	existing := &model.CustomerService{ServiceID: id}
	return db.Model(existing).Updates(updates).Error
}

func DeleteService(db *gorm.DB, id int) error {
	return db.Delete(&model.CustomerService{}, id).Error
}
